<template>
  <div class="news-detail-container">
    <el-card v-if="newsDetail" class="news-card">
      <template #header>
        <div class="card-header">
          <h1>{{ newsDetail.title }}</h1>
          <div class="news-meta">
            <span class="publish-time"
              >发布时间: {{ newsDetail.creattime }}</span
            >
            <span v-if="newsDetail.username" class="author"
              >作者: {{ newsDetail.username }}</span
            >
          </div>
        </div>
      </template>
      <div class="news-content">
        <p>{{ newsDetail.content }}</p>
      </div>
      <div class="back-button">
        <el-button @click="goBack">返回新闻列表</el-button>
      </div>
    </el-card>
    <div v-else class="loading">
      <el-skeleton v-if="loading" :rows="5" animated />
      <div v-else class="no-data">暂无数据</div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import api from "@/util/service";
import { ElMessage } from "element-plus";

const route = useRoute();
const router = useRouter();
const newsDetail = ref(null);
const loading = ref(true);

onMounted(() => {
  fetchNewsDetail();
});

const fetchNewsDetail = async () => {
  const newsId = sessionStorage.getItem("news");

  if (!newsId) {
    ElMessage({
      message: "新闻ID不存在",
      type: "error",
    });
    loading.value = false;
    return;
  }

  try {
    const params = { newsid: newsId };
    const response = await api.post("/tnews/newdetail", params);
    if (response.code === 200) {
      newsDetail.value = response.data;
    } else {
      ElMessage({
        message: "获取新闻详情失败",
        type: "error",
      });
    }
  } catch (error) {
    console.error("获取失败:", error);
    ElMessage({
      message: "获取新闻详情失败",
      type: "error",
    });
  } finally {
    loading.value = false;
  }
};

const goBack = () => {
  router.go(-1);
};
</script>

<style scoped>
.news-detail-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.card-header h1 {
  margin: 0;
  color: #333;
  font-size: 24px;
}

.news-meta {
  margin-top: 10px;
  color: #666;
  font-size: 14px;
}

.news-meta span {
  margin-right: 20px;
}

.news-content {
  min-height: 200px;
  padding: 20px 0;
  font-size: 16px;
  line-height: 1.6;
}

.back-button {
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.loading {
  padding: 50px 0;
}

.no-data {
  text-align: center;
  font-size: 18px;
  color: #999;
}
</style>
